Ext.namespace("Gfa.ext4struts");
Gfa.ext4struts.BaseView = function() {
	this.doLayout();
};
Gfa.ext4struts.BaseView.prototype = {
	// public properties
	fields : null,
	cmDefinition : null,
	fatherHiddenId : null,
	sonEditFormId : null,
	sonId : null,	// 子表主键名
	sonsName : null, // 子表集合名称，如shipOutDetails
	divId : null,
	btnAddSonId : null,
	btnDeleteSonId : null,
	btnCancelSonId : null,
	dwrService : null,
	dwrLoadSonMethod : null,
	// private
	cm : null,
	ds : null,
	grid : null,
	editingRowIdx : -1,
	
	// methods
	initData : function(){
		
	},
	getSelections : function() {
		if (!this.grid.selModel.hasSelection())
			return;
		return this.grid.selModel.getSelections();
	},
	createNewRecord : function(initProp) {
		var data = {};
		Ext.each(this.fields, function(f) {
			if (f.name && f.name.length > 0) {
				var v = {};
				if (f.defaultValue != null) {
					v = f.defaultValue;
				} else if (f.type === 'int' || f.type === 'float') {
					v = 0;
				} else {
					v = '';
				}
				data[f.name] = v;
			}
		});
		data['rowStatus'] = Gfa.GlobalConstant.ROWSTATUS_ADDED;
		Ext.apply(data, initProp);
		var newRecord = new Ext.data.Record(data);
		newRecord.fields = this.fields;
		return newRecord;
	},
	insertNewRecord : function() {
		var record = this.createNewRecord();
		this.grid.store.insert(0, record);
		this.grid.store.afterEdit(record);
		return record;
	},
	updateObject2Record : function(obj, record) {
		record.beginEdit();
		var fs = record.fields;
		for (var index = 0; index < fs.length; index++) {
			var f = {};
			if (fs.items == null || fs.items == undefined) {
				f = fs[index];
			} else {
				f = fs.items[index];
			}
			var fieldValue = obj[f.name];
			if (fieldValue != null && fieldValue != undefined) {
				record.set(f.name, fieldValue);
			}
		}
		record.endEdit();
		return this;
	},
	refreshRowData : function(grid, rowIdx, e) {
		if (this.editingRowIdx == rowIdx) {
			return;
		}
		var originalEditedRowIdx = this.editingRowIdx;
		if (originalEditedRowIdx != null && originalEditedRowIdx >= 0) {
			originalEditedRec = this.ds.getAt(originalEditedRowIdx);
			if (originalEditedRec) {
				var obj = [];
				FormUtils.convertSimpleForm2Object(this.sonEditFormId, obj);
				this.updateObject2Record(obj, originalEditedRec);
				if (originalEditedRec.dirty
						&& originalEditedRec.data.rowStatus != Gfa.GlobalConstant.ROWSTATUS_ADDED
						&& originalEditedRec.data.rowStatus != Gfa.GlobalConstant.ROWSTATUS_DELETED) {
					originalEditedRec.set('rowStatus', Gfa.GlobalConstant.ROWSTATUS_MODIFIED);
				}
			}
		}
		this.editingRowIdx = rowIdx;
		editingRec = this.ds.getAt(rowIdx);
		if (editingRec) {
			FormUtils.convertSimpleObject2Form(editingRec.data, this.sonEditFormId);
		}
	},
	// add
	addAction : function() {
		this.refreshRowData(null, -1, null);
		rec = this.insertNewRecord();
		if (this.grid.selModel.select)// cellSelection
			this.grid.selModel.select(0, 0);
		else
			this.grid.selModel.selectRow(0);
		FormUtils.convertSimpleObject2Form(rec.data, this.sonEditFormId);
		this.editingRowIdx = 0;
	},	
	// delete
	deleteAction : function(){
		var records = this.getSelections();
		if (records) {
			for (var i = 0; i < records.length; i++) {
				var record = records[i];
				if (record.data.rowStatus === Gfa.GlobalConstant.ROWSTATUS_ADDED)
					this.grid.store.remove(record);
				else {
					Ext.MessageBox.confirm('Prompt','Do you really want to delete the selected record?',function(choice){
						if(choice == 'yes'){
							record.set('rowStatus', Gfa.GlobalConstant.ROWSTATUS_DELETED);
						}
					});
				}
			}
		}
	},
	// cancel
	cancelAction : function() {
		var records = this.getSelections();
		if (records) {
			for (var i = 0; i < records.length; i++) {
				var record = records[i];
				if (record.data.rowStatus === Gfa.GlobalConstant.ROWSTATUS_ADDED)
					this.grid.store.remove(record);
				else {
					record.reject();
					record.set('rowStatus', Gfa.GlobalConstant.ROWSTATUS_UNCHANGED);
					FormUtils.convertSimpleObject2Form(record.data, this.sonEditFormId);
				}
			}
		}
	},
	// Create Reader Definition
	createReaderDefinition : function(fields){
		var readerDefinition = [];
		for(var index = 0; index < fields.length; index ++){
			readerDefinition[readerDefinition.length] = fields[index].name;
		}
		return readerDefinition;
	},
	// initElement
	initElement : function() {
		// ds
		var vReaderDefinition = this.createReaderDefinition(this.fields);
		this.ds = new Ext.data.Store({
			proxy : new Gfa.data.DwrProxy(),
			reader : new Gfa.data.DwrReader({}, vReaderDefinition)
		});
		var vDwrService = this.dwrService;
		var vDwrLoadSonMethod = this.dwrLoadSonMethod;
		var vFatherHiddenId = this.fatherHiddenId;
		this.ds.on('beforeLoad', function(store, options) {
			store.proxy.DWR = vDwrService;
			options.params = {
				dwrMethod : vDwrLoadSonMethod,
				dwrArguments : [Ext.get(vFatherHiddenId).getValue()]
			}
		});
		this.ds.load();
		// cm
		this.cm = new Ext.grid.ColumnModel(this.cmDefinition);
		this.cm.defaultSortable = true;
		// grid
		this.grid = new Ext.grid.EditorGridPanel({
			ds : this.ds,
			cm : this.cm,
			sm : new Ext.grid.RowSelectionModel({
				singleSelect : true
			}),
			border : false,
			loadMask : true,
			autoScroll : true,
			clicksToEdit : 0,
			height : 200,
			bodyStyle : "width:100%",
			autoWidth : true,
			enableHdMenu : false,
			enableColumnResize : true,
			enableColumnMove : false,
			draggable : false,
			enableDragDrop : false
		});
		// row color
		this.grid.getView().getRowClass = function(rec, index) {
			if (rec.data.rowStatus == Gfa.GlobalConstant.ROWSTATUS_ADDED) {
				return 'gfa-row-added';
			} else if (rec.data.rowStatus == Gfa.GlobalConstant.ROWSTATUS_DELETED) {
				return 'gfa-row-deleted';
			} else if (rec.data.rowStatus == Gfa.GlobalConstant.ROWSTATUS_MODIFIED) {
				return 'gfa-row-modified';
			} else
				return '';
		};
		// edit
		this.grid.on('rowClick', this.refreshRowData, this);
		Ext.Panel.prototype.border = false;
		this.grid.render(this.divId);
	},
	initListener : function(){
		// 子表按钮监听
		if(this.btnAddSonId && Ext.get(this.btnAddSonId)){
			Ext.get(this.btnAddSonId).addListener('click', this.addAction, this);
		}
		if(this.btnDeleteSonId && Ext.get(this.btnDeleteSonId)){
			Ext.get(this.btnDeleteSonId).addListener('click', this.deleteAction, this);
		}
		if(this.btnCancelSonId && Ext.get(this.btnCancelSonId)){
			Ext.get(this.btnCancelSonId).addListener('click', this.cancelAction, this);		
		}
	},
	// doLayout
	doLayout : function(){
		this.initData();
		this.initElement();
		this.initListener();
	}
};
Ext.namespace("Gfa.ext4struts.utils");
// save
Gfa.ext4struts.utils.saveAction = function() {
	var _fatherEditFormId = this.fatherConfig.fatherEditFormId;
	var _fatherId = this.fatherConfig.fatherId;
	var _dwrService = this.fatherConfig.dwrService;
	var _dwrSaveOrUpdateFatherMethod = this.fatherConfig.dwrSaveOrUpdateFatherMethod;
	var _bindFatherMethod = this.fatherConfig.bindFatherMethod;
	var _sonConfigs = this.sonConfigs;
	var _beforeSaveFunction = this.beforeSaveFunction;
	var _afterSaveFunction = this.afterSaveFunction;
	
	// refresh son grid
	Ext.each(_sonConfigs, function(sonConfig) {
		sonConfig.refreshRowData(null, -1, null);
	});

	// father
	var obj = FormUtils.convertSimpleForm2Object(_fatherEditFormId, TableUtils ._getDomObjById(_fatherEditFormId).data);
	if (obj[_fatherId] != "" && obj[_fatherId] != null
			&& obj[_fatherId] != undefined) {
		//modified status
		obj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_MODIFIED;
	} else {
		//new add status
		obj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_ADDED;
	}

	// son
	Ext.each(_sonConfigs, function(sonConfig) {
		var sons = [];
		var vSonId = sonConfig.sonId;
		var vGridStoreDataItems = sonConfig.grid.store.data.items;
		Ext.each(vGridStoreDataItems, function(item) {
			var objj = item.data;
			if (objj[vSonId] == null || objj[vSonId] == undefined || objj[vSonId] == '') {
				objj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_ADDED;
			}
			sons[sons.length] = objj;
		});
		obj[sonConfig.sonsName] = sons;
	});

	if(_beforeSaveFunction){
		var validateResult = _beforeSaveFunction(obj);
		if(validateResult == false){
			return;
		}
	}
	
	var vDs = [];
	Ext.each(_sonConfigs, function(sonConfig) {
		vDs[vDs.length] = sonConfig.ds;
	});
	_dwrService[_dwrSaveOrUpdateFatherMethod](obj, function(result) {
		_bindFatherMethod();
		Ext.each(vDs, function(ds) {
			ds.load();
		});
		if(_afterSaveFunction){
			_afterSaveFunction(result);
		}
	});
}